package linkedlist.basic;

import linkedlist.ListNode;

/**
 * @Classname : SwapNodesInPairs
 * @Description :
 * <a href="https://leetcode.cn/problems/swap-nodes-in-pairs/">24. 两两交换链表中的节点</a>
 * @Author : chentianyu
 * @Date 2022/12/24 16:52
 */


public class SwapNodesInPairs {
    public ListNode swapPairs(ListNode head) {
        ListNode ans = new ListNode();
        ListNode pre = ans, cur = head;
        while (cur != null && cur.next != null) {
            ListNode node1 = cur;
            ListNode node2 = cur.next;
            cur = cur.next.next;

            pre.next = node2;
            node2.next = node1;
            node1.next = null;
            pre = node1;
        }
        // 可能存在奇数节点
        pre.next = cur;
        return ans.next;
    }
}
